// 导入模块
import {createRouter, createWebHistory} from "vue-router";

// 导入页面加载的进度条工具
import NProgress from 'nprogress'
// 导入进度条的样式文件
import "nprogress/nprogress.css";
// 进行一些配置
NProgress.configure({
    showSpinner: false  // 关闭右上角螺旋加载提示
});

// 定义路由信息
const routes = [{
    path: "/",
    redirect: "/index"
}, {
    path: "/login",
    name: "login",
    component: () => import("../pages/Login.vue")
}, {
    path: "/index",
    name: "index",
    // 配置重定向
    redirect: '/index/welcome',
    component: () => import("../pages/Index.vue"),
    children: [
        // 配置二级路由
        {
            path: "/index/welcome",
            name: "welcome",
            component: () => import("../pages/Welcome.vue")
        },
        {
            path: "/index/user",
            name: "user",
            component: () => import("../pages/user/User.vue")
        },
        {
            path: "/index/useradd",
            name: "useradd",
            component: () => import("../pages/user/UserAdd.vue")
        },
        {
            path: "/index/pay",
            name: "pay",
            component: () => import("../pages/pay/Pay.vue")
        }
    ]
}];

// 创建路由实体
const router = createRouter({
    history: createWebHistory(),
    routes
});

// 添加导航前置守卫
router.beforeEach((to, from, next) => {
    // 开启进度条
    NProgress.start();
    console.log("前置导航守卫");
    let token = window.sessionStorage.getItem("token");
    // 可以判断用户是否登录，如果登录直接放行，如果没有登录跳转到登录页面
    if (to.name === 'login') {
        // 直接放行
        next();
    } else {
        // 非登录组件，要判断token
        if (!token) {
            // 没有登录
            next({name: 'login'});
        } else {
            next();
        }
    }
});

// 定义当前的后置钩子
router.afterEach((to, from) => {
    // 关闭进度条
    NProgress.done();
});


// 暴露出路由实例
export default router;
